package com.linwen.javase.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName _06LockDIYThread
 * @Description
 * @Author lin
 * @Date 2022/4/20 下午11:42
 * @Version V1.0
 *
 * 定制化线程间通信
 * a线程执行5次  b线程执行10次  c线程执行15次  依次执行
 *
 */
public class _06LockDIYThread {
    public static void main(String[] args) {
        LockDIY diy = new LockDIY();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                diy.print5(i);
            }
        },"AAA").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                diy.print10(i);
            }
        },"BBB").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                diy.print15(i);
            }
        },"CCC").start();
    }
}

class LockDIY{
    private int flag = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();

    public void print5(int loop){
        lock.lock();
        try {
            while (flag!=1){
                condition.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+" 第"+loop+"轮"+i);
            }
            flag = 2;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print10(int loop){
        lock.lock();
        try {
            while (flag!=2){
                condition1.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+" 第"+loop+"轮"+i);
            }
            flag = 3;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print15(int loop){
        lock.lock();
        try {
            while (flag!=3){
                condition2.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+" 第"+loop+"轮"+i);
            }
            flag = 1;
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
